package com.fnzn.entranceGuard.util;

import com.fnzn.entranceGuard.util.ApiTokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wf_sxf@163.com
 * @date 2018/5/24 10:53
 */
public class UserUtils {

    @Value("${gate.api.tokenHead}")
    private static  String tokenPrefix ;
    private static String tokenHead ="access-token";

    /**
     * 根据请求heard中的token获取用户角色
     *
     * @param httpServletRequest request
     * @return 角色名
     */
    public static List<String> getRole(HttpServletRequest httpServletRequest) {
        String token = getToken(httpServletRequest);
        Claims claims = ApiTokenUtil.getClaimsFromToken(token);
        String userId =  (String)claims.get(ApiTokenUtil.CLAIM_KEY_USERNAME);
        List<String> roleNames = (List<String>) claims.get("authorities");
        return roleNames;
    }
    /**
     * 根据请求heard中的token获取用户ID
     *
     * @param httpServletRequest request
     * @return 角色名
     */
    public static String getUserId(HttpServletRequest httpServletRequest) {
        String token = getToken(httpServletRequest);
        if(StringUtils.isBlank(token)){
            return null;
        }
        token = token.substring("ApiGateToken".length());
        Claims claims = ApiTokenUtil.getClaimsFromToken(token);
        if(claims != null) {
            return (String)claims.get(ApiTokenUtil.CLAIM_KEY_USERNAME);
        }
        return null;
    }
    /**
     * 获取请求中token
     *
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHead);
        return token;
    }
}
